<?php
namespace Common\Models;
use Common\BaseModel;

class BShopSkuValue extends BaseModel
{
    public $res;
    public $expire;

    public function initialize()
    {
        parent::initialize();
        $this->setSource('b_shop_sku_value');
    }


    /**
     * 根据 key属性 获取所有value值
     */
    public function keyValueList($vid)
    {
        $phql   = "SELECT b.id as value_id,b.value_name,a.key_name,a.id as key_id FROM b_shop_sku_key AS a 
LEFT JOIN b_shop_sku_value AS b ON b.key_id = a.id 
WHERE a.id IN ($vid)";
        $rows = $this->getDI()->get('dbMaster')->fetchAll($phql);
        foreach ($rows as $val) {
            $tmp[$val['key_name'] . '-' . $val['key_id']][] = $val;
        }
        $result = [];
        foreach ($tmp as $key => $val) {
            $keyIds            = explode('-', $key);
            $kTemp             = [];
            $kTemp['key_name'] = $keyIds[0];
            $kTemp['key_id']   = $keyIds[1];
            foreach ($val as $vVal) {
                $valTemp['value_id']   = $vVal['value_id'];
                $valTemp['value_name'] = $vVal['value_name'];
                $kTemp['value'][]      = $valTemp;
            }
            $result[] = $kTemp;
        }
        return $result;
    }

    /**
     * 根据value_ids的值获取 value-name
     */
    public function getValueName($value_ids)
    {
        if($value_ids){
            $id                  = implode(',', explode('_', $value_ids));
        }else{
            $id = "-1";
        }
        $where['conditions'] = "id in ($id)";
        $valueArr            = $this->find($where)->toarray();
        $sku_name            = '';
        if (!empty($valueArr)) {
            $sku_name = implode(' ', array_column($valueArr, 'value_name'));
        }
        return $sku_name;
    }


    /**
     * 根据value值获取key
     */
    public function getValueKeyName($value_ids){
        $phql   = "SELECT v.id as value_id,v.value_name,k.id as key_id,key_name FROM b_shop_sku_value AS v
LEFT JOIN b_shop_sku_key AS k ON k.id = v.key_id
WHERE v.id IN ($value_ids)";
        $rows = $this->getDI()->get('dbMaster')->fetchAll($phql);
        $valueKeyName="";
        foreach($rows as $key=>$value){
            $rows[$key]['value_key'] = "{$value['key_name']}:{$value['value_name']}";
            $valueKeyName .= $rows[$key]['value_key'] ." ";
        }
        $getList['list'] = $rows;
        $getList['value_key_name'] = $valueKeyName;
        return $getList;
    }

}
